import { useSearchParams as useRemixSearchParams } from '@remix-run/react';
import { useConfig } from './D8dConfigProvider.tsx';
import { useCallback, useMemo } from 'react';

/**
 * 用于获取和设置URL查询参数的hook
 * 
 * 返回：
 * - searchParams: URLSearchParams 对象
 * - setSearchParams: 用于更新查询参数的函数
 */
export const useSearchParams = (): [URLSearchParams, (params: Record<string, string> | URLSearchParams) => void] => {
  const { useSpaRouter } = useConfig();
  const [remixSearchParams, setRemixSearchParams] = useRemixSearchParams();
  
  // 在SPA模式下，自定义实现搜索参数
  const customSearchParams = useMemo(() => {
    if (!useSpaRouter) {
      return remixSearchParams;
    }
    
    return new URLSearchParams(window.location.search);
  }, [useSpaRouter, remixSearchParams, window.location.search]);
  
  // 设置搜索参数的函数
  const setCustomSearchParams = useCallback((params: Record<string, string> | URLSearchParams) => {
    if (!useSpaRouter) {
      setRemixSearchParams(params);
      return;
    }
    
    // 将参数转换为URLSearchParams
    const searchParams = params instanceof URLSearchParams ? 
      params : 
      new URLSearchParams(Object.entries(params));
    
    // 构建新的URL
    const newUrl = new URL(window.location.href);
    newUrl.search = searchParams.toString();
    
    // 使用history API更新URL
    window.history.pushState({}, '', newUrl.toString());
    
    // 触发popstate事件以通知路由变化
    window.dispatchEvent(new PopStateEvent('popstate', { state: {} }));
  }, [useSpaRouter, setRemixSearchParams]);
  
  return [
    useSpaRouter ? customSearchParams : remixSearchParams,
    setCustomSearchParams
  ];
}; 